class Syn
  def self.cron_syn
    print "Syn to sqlite to postgres\n"
    print "vacuum...\n"
    Weekly.connection.execute "vacuum;"
    print "weekly\n"
    PgWeekly.transaction do
      Weekly.all(:conditions => ["id > ? and wid is not null", PgWeekly.maximum('id') || 0]).each do |weekly|
	    PgWeekly.connection.execute "insert into #{PgWeekly.table_name} (id) values ('#{weekly.id}');"
	    PgWeekly.find(weekly.id).update_attributes! weekly.attributes
      end
    end
	max_weekly_id = PgWeekly.maximum('id') || 0
    print "weeklyresult\n"
	result_count = 0
	while true do
      results = WeeklyResult.all(:conditions => ["id > ? and weekly_id <= ?", PgWeeklyResult.maximum('id') || 0, max_weekly_id], 
	       :limit => 1000, :order => "id")
	  break if results.empty?
	  result_count += results.size
	  p result_count if (result_count % 17).zero?
      PgWeeklyResult.transaction do   
	  results.each do |result|
	    PgWeeklyResult.connection.execute "insert into #{PgWeeklyResult.table_name} (id) values ('#{result.id}');"
	    PgWeeklyResult.find(result.id).update_attributes! result.attributes
      end
      end
	end
    print "weeklyexcept\n"
    PgWeeklyExcept.transaction do
      WeeklyExcept.all(:conditions => ["id > ? and weekly_id <= ?", PgWeeklyExcept.maximum('id') || 0, max_weekly_id]).each do |weekly_except|
	    PgWeeklyExcept.connection.execute "insert into #{PgWeeklyExcept.table_name} (id) values ('#{weekly_except.id}');"
	    PgWeeklyExcept.find(weekly_except.id).update_attributes! weekly_except.attributes
      end
    end
    print "vacuum...\n"
    PgWeekly.connection.execute "vacuum;"
    system "cd ~/ranking/ && rake tmp:cache:clear"
  end
end
